/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.search.view;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import offset.nodes.Constants;
import offset.nodes.server.view.list.DummyMap;
import offset.nodes.server.workflow.model.WorkflowModel;

/**
 *
 * @author Walter Lütgenau
 */
public class NodeToMapWrapper {

    Session session;
    Node node;
    WorkflowModel workflowModel;
    Columns columns;

    public NodeToMapWrapper(Session session, Node node) {
        this.session = session;
        this.node = node;
        this.workflowModel = new WorkflowModel(session);
        columns = new Columns();
    }

    class Columns extends DummyMap {

        public Object get(Object key) {
            try {
                if (key instanceof String && Constants.JCR_PATH.equals((String) key))
                    return node.getPath();

                Value value = node.getProperty((String) key).getValue();
                if (value == null)
                    return "";
                return value.getString();
            } catch (RepositoryException e) {
                return "";
            }
        }
    }

    public Columns getColumns() {
        return this.columns;
    }

    public String getViewReference() throws RepositoryException {
        if (workflowModel.isWorkflowDocument(node.getProperty(Constants.JCR_PRIMARY_TYPE).getString()))
            return "?ref=" + node.getProperty(Constants.JCR_UUID).getString() + "&" + Constants.PAR_CONTENT_TYPE + "=" + Constants.CONTENT_TYPE_WORKFLOW;

        /*
        String defaultTemplateInstanceUUID = virtualModel.getDefaultTemplateUUID(node.getProperty(Constants.JCR_PRIMARY_TYPE).getString());
        if (defaultTemplateInstanceUUID != null)
            return "?ref=" + node.getProperty(Constants.JCR_UUID).getString() +
                    "&" + Constants.PAR_TEMPLATE_INSTANCE_REFERENCE + "=" + defaultTemplateInstanceUUID +
                    "&" + Constants.PAR_CONTENT_TYPE + "=" + Constants.CONTENT_TYPE_VIRTUAL;
       */

        return getDataReference();
    }

    public String getDataReference() throws RepositoryException {
        return node.getPath();
    }
}
